package com.gary.controller;

import com.alibaba.fastjson.JSON;
import com.gary.config.MyRedisProperties;
import com.gary.entity.HttpSd;
import com.gary.springcloud.service.CommonService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author peng_rui
 * @date 2022/2/25
 */
@RestController
public class HttpSdController {

    @Resource
    private MyRedisProperties myRedisProperties;

    @Value("${prometheus.appInfo.tags:uat,dev}")
    private String[] tags;

    @Resource
    private CommonService commonService;

    @RequestMapping(value = "/api/hosts", method = RequestMethod.GET)
    public List<HttpSd> httpSdConfigJson() {
        List<HttpSd> list = new ArrayList<>();
        //1
        HttpSd httpSd = new HttpSd();
        ArrayList<String> hostList = new ArrayList<>();
        hostList.add("localhost:10046");
        httpSd.setTargets(hostList);

        HashMap<String, String> map = new HashMap<>();
        map.put("appName", "gary-prometheus");
        map.put("idcName", "阿里云");
        httpSd.setLabels(map);
        list.add(httpSd);
        return list;
    }

    @RequestMapping(value = "/api/runtime", method = RequestMethod.GET)
    public String  runtimeExec(@RequestParam("ip") String ip, @RequestParam("port") Integer port) {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process process = runtime.exec("nc -vz " + ip +  " " + port);
            BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader stderrReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line;
            StringBuffer outSb = new StringBuffer();
            while ((line = stdoutReader.readLine()) != null) {
                System.out.println(line);
                outSb.append(line);
            }
            StringBuffer errorSb = new StringBuffer();
            while ((line = stderrReader.readLine()) != null) {
                System.out.println(line);
                errorSb.append(line);
            }
            int exitVal = process.waitFor();
            System.out.println("process exit value is " + exitVal);
            return outSb.toString() + "----/n" + errorSb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "empty";
    }


    @RequestMapping(value = "/my-properties", method = RequestMethod.GET)
    public String myProperties() {
        myRedisProperties.showProperties();
        return "myProperties";
    }

    @RequestMapping(value = "/my-nginx", method = RequestMethod.GET)
    public String myNginx() {
        return "my-nginx";
    }

    /**
     * 数据库备份
     * @return
     */
    @RequestMapping(value = "mysql-back", method = RequestMethod.GET)
    public String mysqlBack() throws Exception {
        String username = "root";
        String pwd = "pengrui";
        String url = "127.0.0.1";
        String path = "/home/mydb/";
        //mysqldump -h 127.0.0.1 -uroot -proot mysql user >D:/info/server/var/backupdata/backups.sql
        String dbName = "cloud2020";
        String pathSql = path+"cloud2020bak.sql";
        File fileSql = new File(pathSql);
        File filePath = new File(path);
        //创建备份sql文件
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        if (!fileSql.exists()){
            fileSql.createNewFile();
        }
        //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql
        StringBuffer sb = new StringBuffer();
        sb.append("mysqldump");
        sb.append(" -h"+url);
        sb.append(" -u"+username);
        sb.append(" -p"+pwd);
        sb.append(" "+dbName+" >");
        sb.append(pathSql);
        System.out.println("cmd命令为："+sb);
        System.out.println("开始备份："+dbName);
        Process process = null;
        //判断操作系统 windwos与linux使用的语句不一样
        if(System.getProperty("os.name").toLowerCase().indexOf("windows") > -1){

            process = Runtime.getRuntime().exec("cmd /c"+sb.toString());
        }else if(System.getProperty("os.name").toLowerCase().indexOf("linux") > -1){
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("cd /www/server/mysql/bin/");
            process = runtime.exec("/bin/sh -c"+sb.toString());
        }else{
            throw new Exception("暂不支持该操作系统，进行数据库备份或还原！");
        }
        //设置超时一分钟
        process.waitFor(60000, TimeUnit.MILLISECONDS);
        //输出返回的错误信息
        StringBuffer mes = new StringBuffer();
        String tmp = "";
        BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        while((tmp = error.readLine()) != null){
            mes.append(tmp + "\n");
        }
        if(mes != null || !"".equals(mes) ){
            System.out.println("备份成功!==>"+mes.toString());
        }
        error.close();
        return "ok";
    }

    /**
     * 数据库还原
     * @param username
     * @param pwd
     * @param url
     * @param path
     * @param tableName
     * @throws Exception
     */
    public String dbRestoreMysql(String username,String pwd,String url,String path,String tableName) throws Exception{
        //mysql -hlocalhost -uroot -proot db < /home/back.sql
        String dbName = "mysql";
        StringBuilder sb = new StringBuilder();
        sb.append("mysql");
        sb.append(" -h"+url);
        sb.append(" -u"+username);
        sb.append(" -p"+pwd);
        sb.append(" "+dbName+" <");
        sb.append(path+tableName+".sql");
        System.out.println("cmd命令为："+sb.toString());
        Process process = null;
        //判断操作系统 windwos与linux使用的语句不一样
        if(System.getProperty("os.name").toLowerCase().indexOf("windows") > -1){
            process = Runtime.getRuntime().exec("cmd /c"+sb.toString());
        }else if(System.getProperty("os.name").toLowerCase().indexOf("linux") > -1){
            process = Runtime.getRuntime().exec("/bin/sh -c"+sb.toString());
        }else{
            throw new Exception("暂不支持该操作系统，进行数据库备份或还原！");
        }
        System.out.println("开始还原数据");
        InputStream is = process.getInputStream();
        BufferedReader bf = new BufferedReader(new InputStreamReader(is,"utf8"));
        String line = null;
        while ((line=bf.readLine())!=null){
            System.out.println(line);
        }
        is.close();
        bf.close();
        return "还原成功！";
    }

    @GetMapping("/common")
    public String common() {
        return commonService.common();
    }
}
